﻿@page "/Fin/Receivable/Create"
@using nERP.ViewModel.Fin.ReceivableVMs
@using nERP.Model.Fin
@using System.ComponentModel.DataAnnotations
@inherits BasePage

<div>
    <ValidateForm @ref="vform" Model="@Model" OnValidSubmit="@Submit">
        <Row ItemsPerRow="ItemsPerRow.Three" RowType="RowType.Normal">
            <BootstrapInputGroupLabel @bind-Value="@Model.Entity.ReceivableCode" />
            <BootstrapInputGroup>
                <BootstrapInput @bind-Value="@Model.Entity.ReceivableCode"></BootstrapInput>
                <Button @ref="@btnSN" Icon="fas fa-plus" Text="@WtmBlazor.Localizer["Page.生成号码"]" OnClick="OnCreateSNAsync"></Button>
            </BootstrapInputGroup>
            <Select @bind-Value="@Model.Entity.CustomerId" Items="AllCustomers" PlaceHolder="@WtmBlazor.Localizer["Sys.PleaseSelect"]" IsPopover ShowSearch OnSelectedItemChanged="OnSelectedItemChanged" />
            <Select @bind-Value="@Model.Entity.MakeUserId" Items="AllMakeUsers" PlaceHolder="@WtmBlazor.Localizer["Sys.PleaseSelect"]" IsPopover ShowSearch />
            <DateTimePicker @bind-Value="@Model.Entity.ReceivableDate" />
            <Select @bind-Value="@Model.Entity.SettlementTypeId" Items="AllSettlementTypes" PlaceHolder="@WtmBlazor.Localizer["Sys.PleaseSelect"]" />
            <Select @bind-Value="@Model.Entity.SettlementAccountId" Items="AllSettlementAccounts" PlaceHolder="@WtmBlazor.Localizer["Sys.PleaseSelect"]" />
            <BootstrapInput @bind-Value="@Model.Entity.TotalPrice" Readonly="true" />
            <BootstrapInput @bind-Value="@Model.Entity.Remark" />
            <WTUploadImage @bind-Value="@Model.Entity.InvoicesImage" />
        </Row>
        <Divider Icon="fa-fw fa-solid fa-bookmark" Text="@WtmBlazor.Localizer["_Model._Receivable._ReceivableDetail_Receivable"]" Alignment="Alignment.Left" />


        <Table TItem="ReceivableDetail" @bind-Items="@ReceivableDetailReceivableList" OnDeleteAsync="@OnDeleteAsync" ShowFooter="true" ShowAddButton="false"
               ShowSkeleton="true" IsStriped="true" IsBordered="true" ShowRefresh="false" ShowToolbar="true" ShowExtendButtons="true" IsExcel="true">
            <TableColumns>
                <TableColumn @bind-Field="@context.Seq" Text="@WtmBlazor.Localizer["Page.序号"]" Readonly="true" />
                <TableColumn @bind-Field="@context.ReceivableDetailCode" Text="@WtmBlazor.Localizer["Page.收款明细单号"]" Visible="false" />
                <TableColumn @bind-Field="@context.SaleId" Text="@WtmBlazor.Localizer["Page.销售订单"]" Readonly="true" />
                <TableColumn @bind-Field="@context.Amount4" Text="@WtmBlazor.Localizer["Page.本次结算金额"]">
                    <EditTemplate Context="V">
                        <BootstrapInput @bind-Value="V.Amount4" @onfocusout="()=>Input_OnFocusout(V)" />
                    </EditTemplate>
                </TableColumn>
                <TableColumn @bind-Field="@context.Amount1" Text="@WtmBlazor.Localizer["Page.单据金额"]" Readonly="true" />
                <TableColumn @bind-Field="@context.Amount2" Text="@WtmBlazor.Localizer["Page.已结金额"]" Readonly="true" />
                <TableColumn @bind-Field="@context.Amount3" Text="@WtmBlazor.Localizer["Page.未结金额"]" Readonly="true" />
                <TableColumn @bind-Field="@context.Remark" Text="@WtmBlazor.Localizer["_Admin.Remark"]" />
            </TableColumns>

            <TableToolbarTemplate>
                <TableToolbarButton TItem="ReceivableDetail" Color="Color.Primary" Icon="fa-fw fa-solid fa-pen-to-square" Text="@WtmBlazor.Localizer["Sys.Select"]" OnClickCallback="@ShowDialog" IsDisabled="@string.IsNullOrEmpty(Model.Entity.CustomerId)" />
                <Modal @ref="SaleModal">
                    <ModalDialog Title="选择采购订单" IsCentered IsDraggable="true">
                        <BodyTemplate>
                            <Table TItem="nERP.ViewModel.So.SaleVMs.Sale_View" @ref="SaleTable" IsStriped="true" @bind-SelectedRows="@SelectedRows"
                                   ShowToolbar="true" ShowDefaultButtons="false" IsMultipleSelect="true" ClickToSelect="true" OnQueryAsync="SaleListVMOnSearchSale"
                                   AllowResizing="true" IsPagination="true" AllowDragColumn="true" ShowColumnList="true" ShowSearch="true" SearchTooltip=""
                                   OnResetSearchAsync="OnResetSearchAsync" SearchMode="SearchMode.Top" CollapsedTopSearch="true" ShowSearchText="false">
                                <SearchTemplate>
                                    <ValidateForm Model="@Model2">
                                        <Row ItemsPerRow="ItemsPerRow.Three" RowType="RowType.Inline">
                                            <BootstrapInput @bind-Value="@Model2.Searcher.SaleCode" />
                                        </Row>
                                    </ValidateForm>
                                </SearchTemplate>
                                <TableColumns>
                                    <TableColumn @bind-Field="@context.Sale_SaleCode" Text="@WtmBlazor.Localizer["Page.销售单号"]" />
                                    <TableColumn @bind-Field="@context.Sale_InvoicesDate" Text="@WtmBlazor.Localizer["Page.单据日期"]" FormatString="yyyy-MM-dd" />
                                    <TableColumn @bind-Field="@context.Sale_MakeUser" Text="@WtmBlazor.Localizer["Page.制单人"]" />
                                    @* <TableColumn @bind-Field="@context.Sale_SettlementAccount" Text="@WtmBlazor.Localizer["Page.结算账户"]" /> *@
                                    <TableColumn @bind-Field="@context.Sale_TotalPrice" Text="@WtmBlazor.Localizer["Page.总金额"]" />
                                    <TableColumn @bind-Field="@context.Sale_TotalPrice1" Text="@WtmBlazor.Localizer["Page.已结金额"]" />
                                    <TableColumn @bind-Field="@context.Sale_TotalPrice2" Text="@WtmBlazor.Localizer["Page.未结金额"]" />
                                    <TableColumn @bind-Field="@context.Sale_Remark" Text="@WtmBlazor.Localizer["_Admin.Remark"]" />
                                </TableColumns>
                            </Table>
                        </BodyTemplate>
                        <FooterTemplate>
                            <Button Text="@WtmBlazor.Localizer["Sys.OK"]" Icon="fa-regular fa-square-check" OnClick="@OnConfirm" />
                        </FooterTemplate>
                    </ModalDialog>
                </Modal>
            </TableToolbarTemplate>
            <FooterTemplate>
                <tr style="background-color:gray; font-weight:600; text-align:center;">
                    <td colspan="3">合计：</td>
                    <td style="color:red;">@sumAmount4</td>
                    <td>@sumAmount1</td>
                    <td> @sumAmount2</td>
                    <td> @sumAmount3</td>
                </tr>
            </FooterTemplate>
        </Table>

        <div class="modal-footer table-modal-footer">
            <Button ButtonType="ButtonType.Submit" IsAsync="true" Text="@WtmBlazor.Localizer["Sys.Submit"]" />
            <Button OnClick="OnClose" Text="@WtmBlazor.Localizer["Sys.Close"]" />
        </div>

    </ValidateForm>

</div>



@code {
    [Parameter]
    public string id { get; set; }
    [Parameter]
    public string[] ids { get; set; }
    private ReceivableVM Model = new ReceivableVM();
    private ValidateForm vform { get; set; }
    private string sumAmount1 { get; set; }
    private string sumAmount2 { get; set; }
    private string sumAmount3 { get; set; }
    private string sumAmount4 { get; set; }
    private async Task Submit(EditContext context)
    {

        Model.Entity.ReceivableDetail_Receivable = ReceivableDetailReceivableList.ToList();
        Model.Entity.ReceivableDetail_Receivable.ForEach(x => x.ReceivableDetailCode = Model.Entity.ReceivableCode + x.Seq.ToString());

        await PostsForm(vform, "/api/Fin/Receivable/Create", (s) => "Sys.OprationSuccess");
    }
    public void OnClose()
    {
        CloseDialog();
    }

    private List<SelectedItem> AllCustomers = new List<SelectedItem>();
    private List<SelectedItem> AllMakeUsers = new List<SelectedItem>();
    private List<SelectedItem> AllSettlementAccounts = new List<SelectedItem>();
    private List<SelectedItem> AllSettlementTypes = new List<SelectedItem>();
    private IEnumerable<ReceivableDetail> ReceivableDetailReceivableList { get; set; } = new List<ReceivableDetail>();
    private List<ReceivableDetail> Items { get; set; } = new List<ReceivableDetail>();
    protected override async Task OnInitializedAsync()
    {


        AllCustomers = await WtmBlazor.Api.CallItemsApi("/api/Fin/Receivable/GetCustomers");
        AllCustomers.Insert(0, new SelectedItem { Text = WtmBlazor.Localizer["Sys.PleaseSelect"], Value = "" });
        AllMakeUsers = await WtmBlazor.Api.CallItemsApi("/api/Fin/Receivable/GetFrameworkUsers");
        AllMakeUsers.Insert(0, new SelectedItem { Text = WtmBlazor.Localizer["Sys.PleaseSelect"], Value = "" });
        AllSettlementAccounts = await WtmBlazor.Api.CallItemsApi("/api/Fin/Receivable/GetSettlementAccounts");
        AllSettlementAccounts.Insert(0, new SelectedItem { Text = WtmBlazor.Localizer["Sys.PleaseSelect"], Value = "" });
        AllSettlementTypes = await WtmBlazor.Api.CallItemsApi("/api/Fin/Receivable/GetDicFields结算方式");
        AllSettlementTypes.Insert(0, new SelectedItem { Text = WtmBlazor.Localizer["Sys.PleaseSelect"], Value = "" });

        Model.Entity.ReceivableDate = DateTime.Now;
        Model.Entity.Status = nERP.Model.StatusTypeEnum.Unaudited;
        Model.Entity.MakeUserId = UserInfo.ITCode;
        await base.OnInitializedAsync();
    }
    private Button btnSN { get; set; }
    private async Task OnCreateSNAsync(MouseEventArgs e)
    {
        var SN = await GetNewSN2("收款单", false);
        Model.Entity.ReceivableCode = SN;
        btnSN.SetDisable(true);
    }

    private Task<bool> OnDeleteAsync(IEnumerable<ReceivableDetail> items)
    {
        items.ToList().ForEach(i => Items.Remove(i));

        sums();

        Model.Entity.TotalPrice = Items.Any() ? Items.Sum(x => x.Amount4) : 0;
        return Task.FromResult(true);
    }
    private async Task OnSelectedItemChanged(SelectedItem item)
    {
        await SaleTable.QueryAsync();

        Items = new List<ReceivableDetail>();
        ReceivableDetailReceivableList = Items;

        sums();

        StateHasChanged();
    }

    [System.Diagnostics.CodeAnalysis.NotNull]
    private Modal? SaleModal { get; set; }
    private List<nERP.ViewModel.So.SaleVMs.Sale_View> SelectedRows { get; set; } = [];

    private List<SelectedItem> AllGoodsTypes = new List<SelectedItem>();

    private nERP.ViewModel.So.SaleVMs.SaleListVM Model2 = new nERP.ViewModel.So.SaleVMs.SaleListVM();

    private Task OnResetSearchAsync(nERP.ViewModel.So.SaleVMs.Sale_View item)
    {
        Model2.Searcher = new nERP.ViewModel.So.SaleVMs.SaleSearcher();
        item = new nERP.ViewModel.So.SaleVMs.Sale_View();
        return Task.CompletedTask;
    }
    private async Task<QueryData<nERP.ViewModel.So.SaleVMs.Sale_View>> SaleListVMOnSearchSale(QueryPageOptions opts)
    {
        if (string.IsNullOrWhiteSpace(Model.Entity.CustomerId)) return null;

        Model2.Searcher.CustomerId = Model.Entity.CustomerId;
        return await StartSearch<nERP.ViewModel.So.SaleVMs.Sale_View>("/api/So/Sale/SearchSale", Model2.Searcher, opts);
    }

    private Task ShowDialog(IEnumerable<ReceivableDetail> items) => SaleModal.Toggle();

    [System.Diagnostics.CodeAnalysis.NotNull]
    private Table<nERP.ViewModel.So.SaleVMs.Sale_View>? SaleTable { get; set; }

    private async Task OnConfirm()
    {
        if (SelectedRows.Count > 0)
        {
            var newSR = SelectedRows.Where(x => !Items.Select(i => i.SaleId).Contains(x.Sale_SaleCode)).ToList();

            foreach (var r in newSR)
            {
                var cr = new ReceivableDetail()
                    {
                        ID = Guid.NewGuid(),
                        Seq = (Items.Max(s => s.Seq) ?? 0) + 1,
                        SaleId = r.Sale_SaleCode,
                        Amount1 = r.Sale_TotalPrice,
                        Amount2 = r.Sale_TotalPrice1,
                        Amount3 = r.Sale_TotalPrice2,
                    };

                Items.Insert(Items.Count, cr);
                ReceivableDetailReceivableList = Items;
            }
            sums();
        }
        StateHasChanged();

        await SaleModal.Toggle();
    }
    private void Input_OnFocusout(ReceivableDetail V)
    {
        if (V.Amount4 == null || V.Amount4 <= 0) { V.Amount4 = 0; }
        if (V.Amount2 == null || V.Amount2 <= 0) { V.Amount2 = 0; }
        if (V.Amount3 == null || V.Amount3 <= 0) { V.Amount3 = 0; }
        if (V.Amount1 - V.Amount4 - V.Amount2 < 0)
        {
            V.Amount4 = 0;
            V.Amount3 = V.Amount1 - V.Amount4 - V.Amount2;
        }
        sums();


        Model.Entity.TotalPrice = Items.Any() ? Items.Sum(x => x.Amount4) : 0;
    }

    /// <summary>
    /// 设置合计项
    /// </summary>
    private void sums()
    {
        sumAmount1 = Items.Any() ? Items.Sum(x => x.Amount1)?.ToString("#0.####") : "0";
        sumAmount2 = Items.Any() ? Items.Sum(x => x.Amount2)?.ToString("#0.####") : "0";
        sumAmount3 = Items.Any() ? Items.Sum(x => x.Amount3)?.ToString("#0.####") : "0";
        sumAmount4 = Items.Any() ? Items.Sum(x => x.Amount4)?.ToString("#0.####") : "0";
    }
}
